<?php
namespace Core\annotationhandlers;

use Core\annotations\RequestMapping;
use Core\BeanFactory;

return [
   RequestMapping::class=>function(\ReflectionMethod $method,$instance,$self){
            $path=$self->value;//uri
            $rquest_method=count($self->method)>0?$self->method:['GET'];
            $router_collector=BeanFactory::getBean("RouterCollector");


           $router_collector->addRouter($rquest_method,$path,function ($parms,$ext_params) use($method,$instance){
                // print_r($parms);return;
                /*
                    Array
                        (
                            [uid] => 123
                        )
                */
                // print_r($ext_params);return;注入类对象参数数组
               $inputParams=[];
               $ref_params=$method->getParameters();//得到方法的反射参数
            //    print_r($ref_params);return;
               /*方法参数
               Array
                (
                    [0] => ReflectionParameter Object
                        (
                            [name] => id
                        )
                    [1] => ReflectionParameter Object
                        (
                            [name] => uid
                        )
                )
               */
               foreach ($ref_params as $ref_param){
                //    print_r($ref_param->getName());return;
                //     uid
                // echo "ref_param".PHP_EOL;
                // print_r($ref_param->getClass());return;
                if(isset($parms[$ref_param->getName()])){
                    $inputParams[]=$parms[$ref_param->getName()];
                }else
                {//对象参数,ext_params实例对象数组
                    foreach($ext_params as $ext_param){
                            if($ref_param->getClass() &&$ref_param->getClass()->isInstance($ext_param)){
                                $inputParams[] = $ext_param;
                                // continue;
                                goto end;
                            }
                        }
                        $inputParams[]=false; //bug 如果第一个注入参数是对象，那么参数数组inputParams会多个false,所以不使用continue
                        /*
                            Array(实际是两个参数
                                [0] => Core\http\Request Object
                                [1] =>
                                [2] => 555
                            )
                        */
                        end:
                    }
                }
                // print_r($inputParams);return;
                /*
                Array(
                    [0] => Core\http\Request Object
                    [1] => 555
                )
                */
            
              // return $method->invoke($instance);//执行反射方法
              //调用路由对应方法
              return $method->invokeArgs($instance,$inputParams);

           });
           return $instance;


   }
];